package com.ln.adoms.service;

import com.ln.adoms.entity.Region;
import com.ln.core.orm.hibernate.BaseDao;
import com.ln.core.orm.hibernate.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class RegionService extends BaseService<Region> {
    @Override
    @Resource(name = "regionDao")
    public void setBaseDao(BaseDao<Region> baseDao) {
        this.baseDao = baseDao;
    }

    public Set<Integer> findAllChildRegionIdsByParentId(Integer id) {
        Set<Integer> regionIds = new HashSet<Integer>();
        regionIds.add(id);
        List<Region> list = this.baseDao.findList("parent.id", id);
        if (list != null && !list.isEmpty()) {
            for (Region r : list) {
                regionIds.add(r.getId());
                Set<Integer> childRegionIds = findAllChildRegionIdsByParentId(r.getId());
                if (childRegionIds != null && !childRegionIds.isEmpty()) {
                    regionIds.addAll(childRegionIds);
                }
            }
        }
        return regionIds;
    }

    /**
     * 检查区域2是否属于区域1
     * 区域1的范围 >区域2的范围的情况
     *
     * @return
     */
    public boolean isSameRegion(Integer regionAId, Integer regionBId) {
        if (regionAId == regionBId) {
            return true;
        }
        return isBelong(regionAId, regionBId) || isBelong(regionBId, regionAId);
    }

    private boolean isBelong(Integer bigRegionId, Integer smallRegionId) {
        Region smallRegion = find(smallRegionId);
        Region tempParentRegion = smallRegion.getParent();
        while (true) {
            if (tempParentRegion.getId() == bigRegionId) {
                return true;
            } else {
                tempParentRegion = tempParentRegion.getParent();
            }
            //根节点的ID为0
            if (tempParentRegion.getId() == 0) {
                break;
            }
        }
        return false;
    }

}
